package com.taotao.search.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.Item;
import com.taotao.search.pojo.SearchResult;

@Repository
public class SearchDaoImpl implements SearchDao {
	@Autowired
	private SolrServer solrServer;

	@Override
	public SearchResult search(SolrQuery query) throws Exception {

		QueryResponse response = solrServer.query(query);
		// 取高亮显示
		Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
		SolrDocumentList results = response.getResults();
		List<Item> itemList = new ArrayList<>();
		for (SolrDocument document : results) {
			Item item = new Item();
			item.setId((String) document.get("id"));
			// 取高亮显示的结果
			List<String> list = highlighting.get(document.get("id")).get("item_title");
			if (list != null && list.size() != 0) {
				item.setTitle(list.get(0));
			} else {
				item.setTitle((String) document.get("item_title"));
			}
			item.setImage((String) document.get("item_image"));
			item.setPrice((long) document.get("item_price"));
			item.setSellPoint((String) document.get("item_sell_point"));
			item.setCategoryName((String) document.get("item_category_name"));
			itemList.add(item);
		}
		SearchResult searchResult = new SearchResult();
		searchResult.setRecordCount(results.getNumFound());
		searchResult.setItemList(itemList);

		return searchResult;
	}

}
